﻿
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataInfo;
using KenLib.BusinessManager;

public partial class JOINT_frmJ_StaffAcademicInput : System.Web.UI.Page
{
    protected void Page_PreRender(object sender, EventArgs e)
    {
        ViewState["CountingSubmitJS55"] = Session["CountingSubmitJS55"];
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        ((JOINT_MstPage_JOINT)this.Master).changeTitle("学歴情報登録");
        ((JOINT_MstPage_JOINT)this.Master).HideLiArea("frmJ_StaffAcademicInput");
        //AppCode_Common.ShowEmtyGrid<学歴情報>(grv, 0, "データーがありません。", "");
        //Session["IdEmp"] = 100;

        if (Session["役"] == null)
        {
            Response.Redirect("~/frmD_Login.aspx");
        }

        if (!Page.IsPostBack)
        {
            ddl_学歴区分.Focus();
            Session["CountingSubmitJS55"] = Server.UrlEncode(System.DateTime.Now.ToString());
            ViewState["indexPage"] = 0;
            ViewState["IdCurrent"] = "";
            ViewState["InsertNew"] = "";
            ViewState["TableTempJS55Insert"] = null;
            ViewState["TableTempJS55Update"] = null;
            /* Mode Update */
            if (Request.QueryString["id"] != null)
            {
                int id;
                Int32.TryParse(Request.QueryString.Get("id").ToString(), out id);
                if (id != 0)
                {
                    grv.Visible = false;
                    btn_次.Enabled = false;
                    LoadDataForUpdate(id.ToString());
                    LoadMessageErrorValid();
                    Session["modeStaffAcademicInput"] = "2";
                    int 企業ID = id;
                    string ngaysinh = new 基本情報Manager().getNgaySinh(企業ID);
                    if (ngaysinh.Length >= 10)
                        hfNgaySinh.Value = ngaysinh.Substring(0, 10);

                }
            }
            else
            {
                /*Insert*/
                LoadMessageErrorValid();
                LoadDataGrvForInsert(Session["IdEmp"].ToString());
                Session["modeStaffAcademicInput"] = "1";//Default mode is Insert
                if (Session["IdEmp"] != null && Session["IdEmp"] != "")
                {
                    string ngaysinh = new 基本情報Manager().getNgaySinh(Int32.Parse(Session["IdEmp"].ToString()));
                    if (ngaysinh.Length >= 10)
                        hfNgaySinh.Value = ngaysinh.Substring(0, 10);
                }
            }
        }
    }
   
    protected void btn_戻る_Click(object sender, EventArgs e)
    {
        if (Session["modeStaffAcademicInput"].ToString() == "1")
            Response.Redirect("frmJ_StaffPhysicalExamInput.aspx");
        else if (Session["modeStaffAcademicInput"].ToString() == "2")
            Response.Redirect("frmJ_EmpBasicInfo.aspx");
    }
 
    protected void btn_次_Click(object sender, EventArgs e)
    {
        if (Session["modeStaffAcademicInput"].ToString() == "1")
            Response.Redirect("frmJ_StaffWorkedCompInput.aspx");
    }
    
    /// <summary>
    /// Load thong diep loi cho cac control
    /// </summary>
    private void LoadMessageErrorValid()
    {
        RequiredFieldValidator1.ErrorMessage =  GetError("ER00007");
        RequiredFieldValidator2.ErrorMessage =  GetError("ER00007");
        RequiredFieldValidator3.ErrorMessage =  GetError("ER00001");
        RequiredFieldValidator4.ErrorMessage =  GetError("ER00001");
        RequiredFieldValidator5.ErrorMessage =  GetError("ER00001");
        RequiredFieldValidator6.ErrorMessage =  GetError("ER00001");
        RequiredFieldValidator7.ErrorMessage =  GetError("ER00001");
        //RequiredFieldValidator8.ErrorMessage = "開始時期" + GetError("ER00001");
        RequiredFieldValidator8.ErrorMessage =  GetError("ER00001");
        //RequiredFieldValidator9.ErrorMessage = "終了時期" + GetError("ER00001");
        RequiredFieldValidator9.ErrorMessage =  GetError("ER00001");
        //RegularExpressionValidator1.ErrorMessage = "開始時期" + GetError("ER00002");
        CustomValidator3.ErrorMessage = GetError("ER00002");
        //RegularExpressionValidator2.ErrorMessage = "終了時期" + GetError("ER00002");
        CustomValidator2.ErrorMessage = GetError("ER00002");
        CustomValidator1.ErrorMessage = GetError("ER00005");
        CustomValidator5.ErrorMessage = GetError("ER00005");
    }
    
    /// <summary>
    /// Lay ra ma loi tuong ung tu CSDL
    /// </summary>
    /// <param name="errorid"></param>
    /// <returns></returns>
    private String GetError(string errorid)
    {
        Error er = new Error();
        er.ErrorID = errorid;
        ErrorManager frm_error = new ErrorManager();
        DataTable dt = frm_error.getError(er);
        return dt.Rows[0][2].ToString();
    }

    protected void btn_リセット_Click(object sender, EventArgs e)
    {
        ClearTextPage();
        if (Session["modeStaffAcademicInput"] != null)
        {
            if (Session["modeStaffAcademicInput"] == "2")
            {
                
            }

            // Reload data if user has chosen record in Gridview
            if (Session["modeStaffAcademicInput"] == "1")
            {
                string strIdCurrent = ViewState["IdCurrent"] != null ? ViewState["IdCurrent"].ToString() : "";
                if (strIdCurrent != "")
                {
                    DataTable dt = (DataTable)ViewState["学歴情報TableJS55"];
                    int index = Int32.Parse(ViewState["indexJS55"].ToString());
                    string temp = "";
                    temp = dt.Rows[index]["区分"].ToString();

                    if (temp != "")
                    {
                        ListItem lst = ddl_学歴区分.Items.FindByValue(temp);
                        ddl_学歴区分.SelectedIndex = ddl_学歴区分.Items.IndexOf(lst);
                    }

                    temp = "";
                    temp = dt.Rows[index]["学歴区分"].ToString();

                    if (temp != "") { ListItem lst = DropDownList1.Items.FindByValue(temp); DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(lst); }
                    txt_学校名.Text = dt.Rows[index]["学校名"].ToString();
                    txt_学校住所.Text = dt.Rows[index]["学校住所"].ToString();

                    temp = dt.Rows[index]["専攻区分"].ToString();
                    if (temp == "0")
                    { rdo_男.Checked = true; rdo_女.Checked = false; }
                    else if (temp == "1")
                    { rdo_女.Checked = true; rdo_男.Checked = false; }

                    txt_専攻系列コード.Text = dt.Rows[index]["専攻系列コード"].ToString();
                    txt_専攻学部.Text = dt.Rows[index]["専攻学部"].ToString();
                    txt_専攻学科.Text = dt.Rows[index]["専攻学科"].ToString();
                    txt_専攻内容.Text = dt.Rows[index]["専攻内容"].ToString();
                    txt_専門技術.Text = dt.Rows[index]["専門技術"].ToString();
                    txt_開始時期.Text = dt.Rows[index]["開始時期"].ToString() != "" ? dt.Rows[index]["開始時期"].ToString().Substring(0, 10) : "";
                    txt_終了時期.Text = dt.Rows[index]["終了時期"].ToString() != "" ? dt.Rows[index]["終了時期"].ToString().Substring(0, 10) : "";
                    txt_担当教授名.Text = dt.Rows[index]["担当教授名"].ToString();
                    LoadDataGrvForInsert(Session["IdEmp"].ToString());
                    
                }
            }
        }
    }

    /// <summary>
    /// Xoa sach test tu cac control
    /// </summary>
    private void ClearTextPage()
    {
        ddl_学歴区分.SelectedIndex = 0;
        DropDownList1.SelectedIndex = 0;
        txt_学校名.Text = "";
        txt_学校住所.Text = "";
        rdo_男.Checked = true;
        rdo_女.Checked = false;
        txt_専攻系列コード.Text = "";
        txt_専攻学部.Text = "";
        txt_専攻学科.Text = "";
        txt_専攻内容.Text = "";
        txt_専門技術.Text = "";
        txt_開始時期.Text = "";
        txt_終了時期.Text = "";
        txt_担当教授名.Text = "";
        ddl_学歴区分.Focus();
    }

    /// <summary>
    /// Load du lieu cho gridview mode: Insert
    /// </summary>
    /// <param name="Id"></param>
    private void LoadDataGrvForInsert(String Id)
    {
        DataTable dt = null;
        dt = new 学歴情報Manager().select_dataForModeInsert_55_Vh(Id);
        if (dt.Rows.Count > 0)
        {
            grv.DataSource = dt;
            grv.DataBind();
            ViewState["TableTempJS55Insert"] = dt;
            Session["state"] = "1";
        }
        else
        {
            Session["state"] = "0";
            AppCode_Common.ShowEmtyGrid<学歴情報>(grv, 0, "データーがありません。", "");

        }
    }

    /// <summary>
    /// Load du lieu cho Gridview mode: Update
    /// </summary>
    /// <param name="Id"></param>
    private void LoadDataForUpdate(String Id)
    {
        DataTable dt = null;
        dt = new 学歴情報Manager().select_dataForModeUpdate_55_Vh(Id);
        int index = dt.Rows.Count - 1;
        if (index < 0) return;

        String temp = "";
        temp = dt.Rows[index]["区分"].ToString();

        if (temp != "")
        { 
            ListItem lst = ddl_学歴区分.Items.FindByValue(temp); 
            ddl_学歴区分.SelectedIndex = ddl_学歴区分.Items.IndexOf(lst); 
        }

        temp = "";
        temp = dt.Rows[index]["学歴区分"].ToString();

        if (temp != "")
        { 
            ListItem lst = DropDownList1.Items.FindByValue(temp); 
            DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(lst); 
        }
        txt_学校名.Text = dt.Rows[index]["学校名"].ToString();
        txt_学校住所.Text = dt.Rows[index]["学校住所"].ToString();

        temp = "";
        temp = dt.Rows[index]["専攻区分"].ToString();
        if (temp == "0")
        { rdo_男.Checked = true; rdo_女.Checked = false; }
        else if (temp == "1")
        { rdo_女.Checked = true; rdo_男.Checked = false; }

        txt_専攻系列コード.Text = dt.Rows[index]["専攻系列コード"].ToString();
        txt_専攻学部.Text = dt.Rows[index]["専攻学部"].ToString();
        txt_専攻学科.Text = dt.Rows[index]["専攻学科"].ToString();
        txt_専攻内容.Text = dt.Rows[index]["専攻内容"].ToString();
        txt_専門技術.Text = dt.Rows[index]["専門技術"].ToString();
        txt_開始時期.Text = dt.Rows[index]["開始時期"].ToString();
        txt_終了時期.Text = dt.Rows[index]["終了時期"].ToString();
        txt_担当教授名.Text = dt.Rows[index]["担当教授名"].ToString();
    }

    protected void btn_登録_Click(object sender, EventArgs e)
    {
        if (Session["CountingSubmitJS55"].ToString() == ViewState["CountingSubmitJS55"].ToString())
        {

            学歴情報 obj = new 学歴情報();
            学歴情報Manager _mana = new 学歴情報Manager();

            obj.区分 = Int32.Parse(ddl_学歴区分.SelectedValue);
            obj.学歴区分 = Int32.Parse(DropDownList1.SelectedValue);
            obj.学校名 = ConvertHTMLtoText(txt_学校名.Text);
            obj.学校住所 = ConvertHTMLtoText(txt_学校住所.Text);
            if (rdo_男.Checked == true)
                obj.専攻区分 = 0;
            else if (rdo_女.Checked == true)
                obj.専攻区分 = 1;
            obj.専攻系列コード_1 = ConvertHTMLtoText(txt_専攻系列コード.Text);
            obj.専攻学部 = ConvertHTMLtoText(txt_専攻学部.Text);
            obj.専攻学科 = ConvertHTMLtoText(txt_専攻学科.Text);
            obj.専攻内容 = ConvertHTMLtoText(txt_専攻内容.Text);
            obj.専門技術 = ConvertHTMLtoText(txt_専門技術.Text);
            obj.担当教授名 = ConvertHTMLtoText(txt_担当教授名.Text);
            obj.開始時期 = DateTime.Parse(txt_開始時期.Text);
            obj.終了時期 = DateTime.Parse(txt_終了時期.Text);


            /*Save object to Database*/
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //-----------------------------------------Mode insert-----------------------------------------------------
            ////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (Session["modeStaffAcademicInput"].ToString() == "1")
            {
                obj.社員ID = Int32.Parse(Session["IdEmp"].ToString());
                string Id = ViewState["IdCurrent"].ToString();
                
                if (Id == "")
                {
                    /*---------------This is Insert mode: Insert state------------*/
                    // Check duplicate 
                    // before inserting into DB
                    int check_exists = 0;
                    check_exists = _mana.checkExists学歴情報_InsertMode_JS55(obj);

                    if (check_exists == 1)// exists a duplicate
                    {
                        string MessageCode = GetError("ER00009");
                        Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 01", "alert('" + MessageCode + "');", true);
                    }
                    else
                    {
                        int intIdCurrent = 0;
                        int result = _mana.insert_dataForModeInsert_55_Vh(obj, out intIdCurrent);
                        ViewState["InsertNew"] = intIdCurrent;
                        if (result != 0)
                        {
                            Session["CountingSubmitJS55"] = Server.UrlEncode(System.DateTime.Now.ToString());
                            ClearTextPage();
                            LoadDataGrvForInsert(Session["IdEmp"].ToString());
                        }
                    }
                    
                }
                else
                {
                    /*------------This is Insert mode: Update state----------------------*/
                    // check current row had changed data?
                    // if it had changed, check exists duplicate 

                    obj.ID = Int32.Parse(Id);

                    bool checkStateChanged = false;
                    checkStateChanged = _mana.checkHasChangedData(obj);

                    if (checkStateChanged == false)
                    {
                        //Update information again.
                        int result = _mana.update_dataForModeUpdate_55_Vh(obj);
                        if (result != 0)
                        {
                            ClearTextPage();
                            Session["CountingSubmitJS55"] = Server.UrlEncode(System.DateTime.Now.ToString());
                            LoadDataGrvForInsert(Session["IdEmp"].ToString());
                            btn_登録.Text = "登録";
                            ViewState["IdCurrent"] = "";
                            ViewState["IdCurrent_After"] = Id;
                        }
                    }
                    else
                    { 
                        // Had changed data
                        // Check exist a duplicate
                        obj.社員ID = Int32.Parse(Session["IdEmp"].ToString());
                        int check_exists = 0;
                        check_exists = _mana.checkExists学歴情報_InsertMode_JS55(obj);

                        if (check_exists == 1)
                        {
                            // exists a duplicate. That is not valid
                            string MessageCode = GetError("ER00009");
                            Page.ClientScript.RegisterStartupScript(typeof(Page), "Same 01", "alert('" + MessageCode + "');", true);
                        }
                        else
                        {
                            int result = _mana.update_dataForModeUpdate_55_Vh(obj);
                            if (result != 0)
                            {
                                ClearTextPage();
                                Session["CountingSubmitJS55"] = Server.UrlEncode(System.DateTime.Now.ToString());
                                LoadDataGrvForInsert(Session["IdEmp"].ToString());
                                btn_登録.Text = "登録";
                                ViewState["IdCurrent"] = "";
                                ViewState["IdCurrent_After"] = Id;
                            }
                        }
                    }
                    
                }
            }


            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            //-------------------------------------Mode Update------------------------------------------------------------
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (Session["modeStaffAcademicInput"].ToString() == "2")
            {
                obj.ID = Int32.Parse(Request.QueryString["id"].ToString());
                int result = _mana.update_dataForModeUpdate_55_Vh(obj);
                if (result != 0)
                {
                    ClearTextPage();
                    Session["CountingSubmitJS55"] = Server.UrlEncode(System.DateTime.Now.ToString());
                    Response.Redirect("frmJ_EmpBasicInfo.aspx");
                }
            }
        }
        else
        {
            if (Session["modeStaffAcademicInput"].ToString() == "1")
            {
                ClearTextPage();
                LoadDataGrvForInsert(Session["IdEmp"].ToString());
            }
        }
    }

    protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onclick", "javascript:__doPostBack('ctl00$ContentPlaceHolder1$grv','Load$" + e.Row.RowIndex + "')");
            //e.Row.BackColor = Color.FromName("#E56E94");
            //grv.Rows[1].BackColor = System.Drawing.Color.LightBlue;
            //e.Row.BackColor = System.Drawing.Color.LightBlue;  
        }
    }

    protected void grv_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Load"))
        {
            int pagecurrent = Int32.Parse(ViewState["indexPage"].ToString());
            int index;
            if (pagecurrent == 0)
                index = Int32.Parse(e.CommandArgument.ToString());
            else
                index = Convert.ToInt32(e.CommandArgument) + pagecurrent * 10;
            if (index == -1) return;

            string mode = Session["modeStaffAcademicInput"] != null ? Session["modeStaffAcademicInput"].ToString() : "";
            if ( mode == "1")
            {
                DataTable dt = null;
                //dt = new 学歴情報Manager().select_dataForModeInsert_55_Vh(Session["IdEmp"].ToString());
                dt = (DataTable)ViewState["TableTempJS55Insert"];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string temp = "";
                    temp = dt.Rows[index]["区分"].ToString();

                    if (temp != "")
                    {
                        ListItem lst = ddl_学歴区分.Items.FindByValue(temp);
                        ddl_学歴区分.SelectedIndex = ddl_学歴区分.Items.IndexOf(lst);
                    }

                    temp = "";
                    temp = dt.Rows[index]["学歴区分"].ToString();

                    if (temp != "") 
                    { 
                        ListItem lst = DropDownList1.Items.FindByValue(temp); 
                        DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(lst); 
                    }
                    txt_学校名.Text = dt.Rows[index]["学校名"].ToString();
                    txt_学校住所.Text = dt.Rows[index]["学校住所"].ToString();

                    temp = dt.Rows[index]["専攻区分"].ToString();
                    if (temp == "0")
                    { rdo_男.Checked = true; rdo_女.Checked = false; }
                    else if (temp == "1")
                    { rdo_女.Checked = true; rdo_男.Checked = false; }

                    txt_専攻系列コード.Text = dt.Rows[index]["専攻系列コード"].ToString();
                    txt_専攻学部.Text = dt.Rows[index]["専攻学部"].ToString();
                    txt_専攻学科.Text = dt.Rows[index]["専攻学科"].ToString();
                    txt_専攻内容.Text = dt.Rows[index]["専攻内容"].ToString();
                    txt_専門技術.Text = dt.Rows[index]["専門技術"].ToString();
                    txt_開始時期.Text = dt.Rows[index]["開始時期"].ToString() != "" ? dt.Rows[index]["開始時期"].ToString().Substring(0, 10) : "";
                    txt_終了時期.Text = dt.Rows[index]["終了時期"].ToString() != "" ? dt.Rows[index]["終了時期"].ToString().Substring(0, 10) : "";
                    txt_担当教授名.Text = dt.Rows[index]["担当教授名"].ToString();
                    btn_登録.Text = " 更新";
                    ViewState["IdCurrent"] = dt.Rows[index]["ID"].ToString();
                    ViewState["学歴情報TableJS55"] = dt;
                    ViewState["indexJS55"] = index;
                }
            }
        }
    }

    protected void grv_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        int index = e.NewPageIndex;
        ViewState["indexPage"] = index;
        grv.PageIndex = index;
        LoadDataGrvForInsert(Session["IdEmp"].ToString());
        grv.DataBind();
    }

    protected void grv_PreRender(object sender, EventArgs e)
    {
        //Highlight when insert new
        if (ViewState["InsertNew"] != null && ViewState["InsertNew"] != "")
        {
            if (string.IsNullOrEmpty(ViewState["InsertNew"].ToString()))
                return;

            for (int i = 0; i < grv.Rows.Count; i++)
            {
                string Id = grv.DataKeys[i].Value.ToString();
                if (Id == ViewState["InsertNew"].ToString())
                {
                    grv.Rows[i].CssClass = "insert";
                    ViewState["InsertNew"] = "";
                    break;
                }
            }
        }
        
        //Highlight when has stating Update of insert
        if(ViewState["IdCurrent_After"]!=null)
        {
            if(string.IsNullOrEmpty(ViewState["IdCurrent_After"].ToString()))
            {
                return;
            }
            for (int i = 0; i < grv.Rows.Count; i++)
            {
                string Id = grv.DataKeys[i].Value.ToString();
                if (Id == ViewState["IdCurrent_After"].ToString())
                {
                    grv.Rows[i].CssClass = "update";
                    ViewState["IdCurrent_After"] = "";
                    break;
                }
            }
        }

        //Highlight when it being Update mode
        

    }

    /// <summary>
    /// Chuyen tu chuoi van ban sang ma HTML
    /// </summary>
    /// <param name="temp"></param>
    /// <returns></returns>
    public string ConvertTexttoHTML(string temp)
    {
        temp = temp.Replace("<", "&lt;");
        temp = temp.Replace(">", "&gt;");
        return temp;
    }

    /// <summary>
    /// Chuyen tu ma HTML sang chuoi van ban
    /// </summary>
    /// <param name="temp"></param>
    /// <returns></returns>
    public string ConvertHTMLtoText(string temp)
    {
        temp = temp.Replace("&lt;", "<");
        temp = temp.Replace("&gt;", ">");
        temp = temp.Replace(Convert.ToString((char)13), "<br/>");
        return temp;
    }

}
